package com.ponhu.ea2.goodsCenter.provider.facade.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ponhu.ea2.common.basic.model.ResponseBean;
import com.ponhu.ea2.dto.GoodsPriceDetailsDto;
import com.ponhu.ea2.dto.PhInventoryBaseDto;
import com.ponhu.ea2.dto.PhInventoryGoodsEditDto;
import com.ponhu.ea2.entity.Goods;
import com.ponhu.ea2.entity.GoodsInventoryMd;
import com.ponhu.ea2.entity.Inventory;
import com.ponhu.ea2.enums.SyncAppletTypeEnum;
import com.ponhu.ea2.goodsCenter.provider.biz.OperationRecordLogsCoreService;
import com.ponhu.ea2.goodsCenter.provider.factory.GoodsFactory;
import com.ponhu.ea2.goodsCenter.provider.factory.GoodsFactoryService;
import com.ponhu.ea2.goodsCenter.provider.service.GoodsInventoryMdService;
import com.ponhu.ea2.goodsCenter.provider.service.GoodsService;
import com.ponhu.ea2.goodsCenter.provider.service.InventoryService;
import com.ponhu.ea2.goodsCenter.provider.service.PhinventoryToAmqpService;
import com.ponhu.ea2.goodsCenter.provider.utils.JsonUtils;
import com.ponhu.ea2.goodsCenter.provider.utils.ProBeanUtils;
import com.ponhu.ea2.properties.GoodsProperties;
import com.ponhu.ea2.service.facade.GoodsCenterForChuangjiService;
import com.ponhu.ea2.service.facade.GoodsCenterForThirdPartyService;
import com.ponhu.ea2.service.facade.GoodsCenterForWMSService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;

/**
 * @author luyu
 * @create 2021-11-03 14:37
 */
@Slf4j
@DubboService(version = "1.0.0", retries = -1, interfaceClass = GoodsCenterForThirdPartyService.class, timeout = 10000)
public class GoodsCenterForThirdPartyServiceImpl implements GoodsCenterForThirdPartyService {

    @Resource
    private InventoryService inventoryService;

    @Resource
    private GoodsInventoryMdService goodsInventoryMdService;

    @Resource
    private GoodsService goodsService;

    @Resource
    private GoodsProperties goodsProperties;

    @Resource
    private PhinventoryToAmqpService phinventoryToAmqpService;

    @Resource
    private OperationRecordLogsCoreService operationRecordLogsCoreService;

    @Resource
    private GoodsCenterForChuangjiService goodsCenterForChuangjiService;

    @Override
    public <T extends PhInventoryBaseDto> ResponseBean createGoodsAndInventoryForThirdpaerty(T t) {

        GoodsFactoryService shape1 = GoodsFactory.getShape(t.getClass());
        ResponseBean responseBean = shape1.createOrUpdateGoods(t);
        return responseBean;
    }

    /**
     * 采购中心使用,修改商品中心价格
     *
     * @param goodsPriceDetailsDto
     * @return
     */
    @Override
    public boolean updateGoodsPriceDetails(GoodsPriceDetailsDto goodsPriceDetailsDto) {
        log.info("ERP-寄售改价开始,入参为：{}", JsonUtils.toJson(goodsPriceDetailsDto));
        // 更新商品中心的成本价
        Inventory inventory = inventoryService.getOne(new LambdaQueryWrapper<Inventory>()
                .eq(Inventory::getInventoryCode, goodsPriceDetailsDto.getInventoryCode()));

        if (ObjectUtils.isEmpty(inventory)) return false;

        CompletableFuture<PhInventoryGoodsEditDto> oldFuture = CompletableFuture
                .supplyAsync(() -> {
                    Inventory oldinventory = inventoryService.getOne(new LambdaQueryWrapper<Inventory>()
                            .eq(Inventory::getInventoryCode, goodsPriceDetailsDto.getInventoryCode()));
                    PhInventoryGoodsEditDto oldEditDto = ProBeanUtils.copyProperties(oldinventory, PhInventoryGoodsEditDto.class);
                    oldEditDto.setInventoryId(oldinventory.getId());
                    return oldEditDto;
                });
        if (BooleanUtils.isFalse(((GoodsCenterForThirdPartyServiceImpl)AopContext.currentProxy())
                .updateInventoryCost(inventory,goodsPriceDetailsDto))) {
            throw new RuntimeException("采购修改采购价格,更新失败");
        }
        PhInventoryGoodsEditDto newEditDto = ProBeanUtils.copyProperties(inventory, PhInventoryGoodsEditDto.class);
        newEditDto.setOperatorId(0L);
        newEditDto.setOperatorName("ERP-寄售");
        operationRecordLogsCoreService.operationRecordLogs(oldFuture,
                newEditDto, "采购修改采购价记录操作日志异常", newEditDto);
        // 同步创纪云，跟张星确认过，这里不需要判断是否为云商的货
        log.info("ERP-寄售，推送创纪云开关:{}",goodsProperties.getEnablePushChuangji());
        if(BooleanUtils.isTrue(goodsProperties.getEnablePushChuangji())){
            log.info("ERP-寄售，推送创纪云的货品编码为：{}",goodsPriceDetailsDto.getInventoryCode());
            CompletableFuture.runAsync(() ->
                    goodsCenterForChuangjiService.phInventoryUpdateToChuangji(inventory.getId()));
        }
        CompletableFuture.runAsync(() ->{
            phinventoryToAmqpService.pushDataToAmqp(
                    Arrays.asList(inventory.getInventoryCode()),
                    SyncAppletTypeEnum.GOODS_PRICE.getCode());
        });
        log.info("ERP-寄售改价结束,货品编码{}",inventory.getInventoryCode());
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public Boolean updateInventoryCost(Inventory inventory,GoodsPriceDetailsDto goodsPriceDetailsDto){
        inventory.setInventoryCost(goodsPriceDetailsDto.getPurchasePrice()
                .multiply(new BigDecimal(goodsPriceDetailsDto.getCoefficient()))
                .add(goodsPriceDetailsDto.getPurchasePrice())
                .add(inventory.getMathMaintenancePrice())
                .setScale(2, BigDecimal.ROUND_DOWN));
        return inventoryService.updateById(inventory);
    }
}
